<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace controller;

use service\Auth;
use service\InterfaceCode;
use service\ToolsService;
use think\exception\HttpResponseException;
use think\facade\Config;
use think\facade\Cookie;
use think\facade\Request;
use think\facade\Response;


/**
 * 基础Web接口类
 * Class BasicApi
 * @package controller
 */
class BasicWeb
{
    protected $auth_type = 1;
    /**
     * @var Request Request 实例
     */
    protected $request;

    /**
     * 权限Auth
     * @var Auth
     */
    protected $auth = null;

    /**
     * 默认响应输出类型,支持json/xml
     * @var string
     */
    protected $responseType = 'json';

    protected $_time;

    /**
     * 构造方法
     * @access public
     * @param Request $request Request 对象
     */
    public function __construct(Request $request = null)
    {
        ToolsService::corsOptionsHandler();
        $this->_time = time();
        $this->request = Request::instance();
        // 控制器初始化
        $this->_initialize();

    }


    /**
     * @param int $auth_type 认证类型配置
     * @example 1.开启token验证  2.同时开启token验证和用户登录验证  4.关闭设备和用户登录验证
     */
    protected function _initialize()
    {
        //移除HTML标签
        $this->request->filter('strip_tags');
        $this->auth = Auth::instance();
        $token = $this->request->server('HTTP_TOKEN', $this->request->header('token', Cookie::get('access_token')));
        if(env('APP_ENV') != 'debug') {
            if(!ToolsService::checkSign($this->request->get())) {
                $this->error(InterfaceCode::Invalid_dsig, InterfaceCode::$message[InterfaceCode::Invalid_dsig]);
            }
        }

        // 检测是否需要验证登录
        if ($this->auth_type == 1 || $this->auth_type == 2) {
            // 根据token
            if(!$this->auth->autologin($token)) {
                //初始化
                $this->auth->init($token);
                //检测是否登录
                if (!$this->auth->isLogin()) {
                    $this->error(InterfaceCode::Uid_must_need, InterfaceCode::$message[InterfaceCode::No_such_uid]);
                }
            }
        }else {
            // 如果有传递token才验证是否登录状态
            if ($token) {
                if(!$this->auth->init($token)) {
                    $this->error(InterfaceCode::Token_error, InterfaceCode::$message[InterfaceCode::Token_error]);
                }
            }
        }
    }

    protected function success($data = null, $msg = '', $code = InterfaceCode::SUCCESS, $type = null, array $header = [])
    {
        $header = ToolsService::corsRequestHander();
        $this->result($msg, $data, $code, $type, $header);
    }
    /**
     * 操作失败返回的数据
     * @param string $msg   提示信息
     * @param mixed $data   要返回的数据
     * @param int   $code   错误码，默认为0
     * @param string $type  输出类型
     * @param array $header 发送的 Header 信息
     */
    protected function error($code = 0, $msg = '', $data = null,$type = null, array $header = [])
    {
        $header = ToolsService::corsRequestHander();
        $this->result($msg, $data, $code, $type, $header);
    }

    /**
     * 返回封装后的 API 数据到客户端
     * @access protected
     * @param mixed  $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码，默认为0
     * @param string $type   输出类型，支持json/xml/jsonp
     * @param array  $header 发送的 Header 信息
     * @return void
     * @throws HttpResponseException
     */
    protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
    {
        if(is_null($data)) {
            $data = '';
        }
        $result = [
            'code' => (int) $code,
            'msg'  => $msg,
            'data' => $data,
        ];
        // 如果未设置类型则自动判断
        $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);
        if (isset($header['statuscode'])) {
            $code = $header['statuscode'];
            unset($header['statuscode']);
        }else {
            //未设置状态码,根据code值判断
            $code = $code >= 1000 || $code < 200 ? 200 : $code;
        }
        $response = Response::create($result, $type, $code)->header($header);
        throw new HttpResponseException($response);
    }

    /**
     * 设置验证失败后是否抛出异常
     * @access protected
     * @param bool $fail 是否抛出异常
     * @return $this
     */
    protected function validateFailException($fail = true)
    {
        $this->failException = $fail;
        return $this;
    }


}